new Vue({
  el: '#app',
  data() {
    return {
      form: {
        Article_Name: "",
        page: 1,			//页数
        limit: 10,			//每页数据条数
        token: $.cookie('token'),
      },
      qrcode: 'a',
      Purchase_Order_SerialNumber: '',
      formAcceptance: [],
      formware: {
        Purchase_Receipt_SerialNumber: "",
        Receipt_Date: "",
        Receipt_Type: "",
        Store_SerialNumber: "",
        Children: {
          purchase_receipt_detail: [{
            Purchase_Receipt_Detail_SerialNumber: "",
            Purchase_Receipt_SerialNumber: "",
            Purchase_Order_SerialNumber: "",
            Article_SerialNumber: "",
            Receipt_Quantity: "",
            Amount: ""
          }]
        }
      },
      Wares: [],
      options: [
        {
          label: '仓库',
          value: 0
        },
        // {
        //   label: '店铺',
        //   value: 1,
        // }
      ],
      PayWay: [
        {
          label: '微信支付',
          value: 1,
          url: "../../../admin/images/WXlogo.png",
        },
        {
          label: '支付宝支付',
          value: 2,
          url: "../../../admin/images/zfbfalse.png",
          disabled: true,
        },
        {
          label: '电子汇账',
          value: 3,
          url: "../../../admin/images/dzhz.png",
        },
      ],
      Data: '',
      PayTitle: '请选择支付方式',
      SelectPayway: 0,
      radio: 1,
      wxcode_url: '',
      zfbcode_url: '',
      value: 0,
      disabled: true,
      imageUrl: '',
      Picture_Url: '',
      Purchase_Order_SerialNumber: '',
      formData: {},
      tableData: [{}],		//表格数据
      statistics: {
        Paid_Amount: "",
        Purchase_Amount: ""
      },
      total: 1,
      dialogForm: false,
      dialogVisible: false,
      dialogFormVisible: false,
      dialogFormwareVisible: false,
      dialogPayforVisible: false,
      dialogwxPayforVisible: false,
      dialogzfbPayforVisible: false,
      dialogdzPayforVisible: false,
      dialogPayWayVisible: false,
      Payment: {},
      Paystages: {},
      loading: false,
      title: '',
      fileList: [],
      multipleSelection: [],
      arr: []
    }
  },
  mounted() {
    this.getList(this.form)
  },
  methods: {
    onSerach() {				//查询方法
      this.form.page = 1;
      this.getList(this.form)
    },
    ChangeInput() {
      this.form.page = 1;
      this.getList(this.form)
    },
    getList(data) {     //换页方法
      let _this = this
      $.ajax({
        type: 'POST',
        url: DomainName + "/getPurchaseOrderAllAction",
        data,
        complete: function (XMLHttpRequest) {
          _this.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        success: function (Result) {
          console.log(Result);
          Result.tableData.forEach(item => {
            item.Paid_Amount = Number(item.Paid_Amount)
          })
          _this.statistics.Paid_Amount = parseInt(Result.statistics.Paid_Amount)
          _this.statistics.Purchase_Amount = parseInt(Result.statistics.Purchase_Amount)
          _this.tableData = Result.tableData      //将获取的数据存到表格数据中
          _this.total = parseInt(Result.limit)
        },
        dataType: "json"
      });
    },
    addEnterprise() {//去添加
      window.location.href = './Add.html'
    },
    // 展开详细信息
    ChangePurchase(row) {
      _this = this
      console.log(row.Purchase_Order_SerialNumber)
      // if (!row.Children.purchase_order_detail.length) {
      $.ajax({
        url: DomainName + '/getPurchaseOrderDetailAction',
        type: 'POST',
        data: {
          Purchase_Order_SerialNumber: row.Purchase_Order_SerialNumber,
          token: $.cookie("token")
        },
        success: function (data) {
          console.log(data)
          // data.forEach(item => {
          //   item.Picture_URL = DomainName + item.Picture_URL
          // })
          row.Children.purchase_order_detail = data
          console.log(row.Children.purchase_order_detail)
        },
        dataType: "json"
      });
      // }
    },
    handleSizeChange(val) {
      this.form.page = 1;
      this.form.limit = val;
      this.getList(this.form)
    },
    handleCurrentChange(val) {
      this.form.page = val;
      this.getList(this.form)
    },
    GetInquiry(Primary_Key, i) {//查原值
      let this_ = this
      this_.loading = true
      $.ajax({
        url: DomainName + '/getInquiryIDOriginal?token=' + $.cookie("token"),
        type: 'POST',
        data: {
          Primary_Key_Name: 'Purchase_Order_SerialNumber',
          Primary_Key,
          Data: 'purchase_order',
        },
        success: function (res) {
          console.log(res)
          this_.formData = res[0]
          this_.formData.Row_Status = i
          if (this_.formData.Row_Status = i) {
            this_.AddInquiry(this_.formData, i)
          }
        },
        dataType: "json"
      });
    },
    AddInquiry(formData, i) {//添加
      let this_ = this
      let data = {
        Data: JSON.stringify(
          {
            Modify: { 'purchase_order': [formData] },
          }
        )
      }
      console.log(formData)
      $.ajax({
        url: DomainName + '/getEditAction?token=' + $.cookie("token"),
        type: 'POST',
        data,
        success: function (res) {
          console.log(res)
          if (res.Status == 'success') {
            this_.getList(this_.form)
            if (i == 1) {
              this_.$message({
                message: '付款成功',
                type: 'success'
              })
            }
          }
          this_.loading = false
        },
        dataType: "json"
      });
    },
    Payfor(row, i) {//付款
      // this.loading = true
      if (row.Settled_Enterprise_Info_SerialNumber == '') {
        this.GetInquiry(row.Purchase_Order_SerialNumber, i)
        return
      }
      this.GetPayment(row.Purchase_Order_SerialNumber)
      this.dialogPayWayVisible = true
      this.Purchase_Order_SerialNumber = row.Purchase_Order_SerialNumber
      this.Purchase_Amount = row.Purchase_Amount
    },
    GetPayment(Purchase_Order_SerialNumber) {
      let this_ = this
      $.ajax({
        type: 'POST',
        url: DomainName + '/getInquiryIDAction?token=' + $.cookie("token"),
        data: {
          Primary_Key_Name: 'Purchase_Order_SerialNumber',
          Primary_Key:Purchase_Order_SerialNumber,
          Data: 'purchase_order_paystages',
          isNullEnterprise:true
        },
        success: function (Result) {
          console.log(Result)
          this_.Payment = Result
        },
        error: function () {
          this_.$message.error("操作失败，请稍后再试")
        },
        dataType: "json"
      });
    },
    PayWays(data) {
      this.Paystages = data
      this.dialogPayforVisible = true
      this.dialogPayWayVisible = false
    },
    Acceptance(row, i) {//验收
      // this.dialogFormVisible = true
      sessionStorage.setItem('Purchase_Order_SerialNumber', row.Purchase_Order_SerialNumber)
      window.location.href = './WarehouseAcceptance.html'
      // this.getGoods(row.Purchase_Order_SerialNumber)
      // this.Purchase_Order_SerialNumber = row.Purchase_Order_SerialNumber
    },
    getGoods(Purchase_Order_SerialNumber) {//获取所选商品
      let this_ = this
      $.ajax({
        url: DomainName + '/getInquiryIDOriginal?token=' + $.cookie("token"),
        type: 'POST',
        data: {
          Primary_Key_Name: 'Purchase_Order_SerialNumber',
          Primary_Key: Purchase_Order_SerialNumber,
          Data: 'purchase_order_detail',
          isNullEnterprise: true
        },
        success: function (res) {
          console.log(res)
          this_.formAcceptance = res
          this_.formware.Children.purchase_receipt_detail = []
          this_.formAcceptance.forEach(item => {
            this_.formware.Children.purchase_receipt_detail.push({
              Purchase_Receipt_Detail_SerialNumber: "",
              Purchase_Receipt_SerialNumber: "",
              Purchase_Order_SerialNumber: item.Purchase_Order_SerialNumber,
              Article_SerialNumber: item.Article_SerialNumber,
              Receipt_Quantity: item.Receipt_Quantity,
              Amount: item.Article_UnitPrice
            })
          })
        },
        dataType: "json"
      });
    },
    ModifyGoods() {//修改商品
      let this_ = this
      this.loading = true
      this.formAcceptance.forEach(item => {
        item.Row_Status = '3'
        item.Not_Receipt_Quantity = item.Quantity - item.Receipt_Quantity
      })
      console.log(this.formAcceptance)
      let data = {
        Data: JSON.stringify(
          {
            Modify: { 'purchase_order_detail': this.formAcceptance },
          }
        )
      }
      $.ajax({
        url: DomainName + '/getEditAction?token=' + $.cookie("token"),
        type: 'POST',
        data,
        success: function (res) {
          console.log(res)
          if (res.Status == 'success') {
            this_.$message({
              message: '验收成功',
              type: 'success'
            });
            this_.getList(this_.form)
            this_.dialogFormVisible = false
          }
          this_.loading = false
        },
        dataType: "json"
      });
      this.GetInquiry(this.Purchase_Order_SerialNumber, 6)
    },
    Warehousing(row, i) {//入库
      // this.dialogFormwareVisible = true
      this.Purchase_Order_SerialNumber = row.Purchase_Order_SerialNumber
      window.location.href = `./Addinbound.html?Purchase_Order_SerialNumber=` + this.Purchase_Order_SerialNumber
      // this.getWares()
    },
    getWares() {//获取所有可选仓库
      let this_ = this
      $.ajax({
        url: DomainName + '/getInquiryAction?token=' + $.cookie("token"),
        type: 'POST',
        data: {
          Data: 'warehouse_info',
        },
        success: function (res) {
          res.forEach(item => {
            this_.Wares.push({
              label: item.Warehouse_Name,
              value: item.Applicable_Type == '0' ? item.Warehouse_SerialNumber : item.Parent_Warehouse_SerialNumber
            })
          })
          this_.getGoods(this_.Purchase_Order_SerialNumber)
          console.log(this_.Wares)
        },
        dataType: "json"
      });
    },
    Sumbit() {// 入库
      let this_ = this
      this_.loading = true
      this.formware.Receipt_Date = getYMDHMSDate()
      console.log(this.formware)
      $.ajax({
        url: DomainName + '/setInventoryAction?token=' + $.cookie("token"),
        type: 'POST',
        data: {
          Data: JSON.stringify({ 'purchase_receipt': [this_.formware] })
        },
        success: function (res) {
          console.log(res)
          if (res.Status == 'success') {
            this_.GetInquiry(this_.Purchase_Order_SerialNumber, 7)
            this_.$message({
              message: '已入库',
              type: 'success'
            });
            this_.dialogFormwareVisible = false
            this_.getList(this_.form)
          }
          this_.loading = false
        },
        dataType: "json"
      });
    },
    editMember(EnterpriseInfo_SerialNumber) {
      sessionStorage.setItem("EnterpriseInfo_SerialNumber", EnterpriseInfo_SerialNumber)
      window.location.href = './Edit.html?EnterpriseInfo_SerialNumber=' + EnterpriseInfo_SerialNumber
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    uploadDetails(file) {
      this.fileList.push({
        name: file.name,
        url: file.type
      })
      let _this = this
      var reader = new FileReader();
      reader.readAsBinaryString(file);
      reader.onload = function (e) {
        var data = e.target.result;
        var wb = XLSX.read(data, {
          type: 'binary' //以二进制的方式读取
        });
        var sheet0 = wb.Sheets[wb.SheetNames[0]];//sheet0代表excel表格中的第一页
        var str = XLSX.utils.sheet_to_json(sheet0);//利用接口实现转换。
        console.log(str);
        //将整体数据分解成每一条，一条上传一次
        let newArr = []
        //1.将接受到数组便利
        //2.将栏目存到_this.sales_unitprice里并去重

      }
    },
    getQRcode(rendermethod, picwidth, picheight, url, id, i) {//获取二维码
      this.loading = false
      this.dialogPayforVisible = false
      $(`#${id}`).qrcode({
        render: rendermethod,
        width: picwidth, //宽度
        height: picheight,//高度
        text: url,//内容
        typeNumber: -1,//计算模
        correctLevel: 2,//二维码纠错级别
        background: "#ffffff",//背景额色
        foreground: "#898888"//二维码额色
      })
    },
    SelectRadio(value) {//点击图片选择支付方式
      if (value == 2) {
        return
      }
      this.radio = value
    },
    Pay() {//选择支付方式
      let _this = this
      this.SelectPayway = this.radio
      this.loading = true
      if (this.SelectPayway == 1) {
        this.PayTitle = '微信支付'
        _this.dialogwxPayforVisible = true
        console.log(_this.wxcode_url)
        if (_this.wxcode_url == '') {
          console.log(_this.Paystages)
          $.ajax({//调用微信支付生成二维码
            url: DomainName + '/PurchaseNativeAction?token=' + $.cookie("token"),
            type: 'POST',
            data: {
              Collection_Type: '微信支付',
              Purchase_Order_Paystages_SerialNumber: _this.Paystages.Purchase_Order_Paystages_SerialNumber
            },
            success: function (res) {
              _this.wxcode_url = res.code_url
              console.log(res)
              _this.getQRcode("table", 200, 200, _this.wxcode_url, 'WeChatPay', 1)
            },
            dataType: "json"
          });
        } else {
          this.dialogPayforVisible = false
          this.loading = false
        }
      } else if (this.SelectPayway == 2) {
        this.PayTitle = '支付宝支付'
        if (_this.zfbcode_url == '') {
          $.ajax({//调用支付宝支付生成二维码
            url: DomainName + '/PurchaseNativeAction?token=' + $.cookie("token"),
            type: 'POST',
            data: {
              Collection_Type: '支付宝支付',
              Purchase_Order_Paystages_SerialNumber: _this.Paystages.Purchase_Order_Paystages_SerialNumber
            },
            success: function (res) {
              _this.zfbcode_url = res.code_url
              console.log(res)
              _this.dialogzfbPayforVisible = true
              _this.getQRcode("table", 200, 200, _this.zfbcode_url, 'AlipayPay', 2)
            },
            dataType: "json"
          });
        } else {
          this.dialogPayforVisible = false
          this.loading = false
        }
      } else {
        this.PayTitle = '电子汇账'
        this.dialogPayforVisible = false
        this.dialogdzPayforVisible = true
        this.loading = false
        $.ajax({
          url: DomainName + '/PurchaseNativeAction?token=' + $.cookie("token"),
          type: 'POST',
          data: {
            Collection_Type: '电子汇账',
            Purchase_Order_Paystages_SerialNumber: _this.Paystages.Purchase_Order_Paystages_SerialNumber
          },
          success: function (res) {
            console.log(res)
            _this.Data = res.Data
            _this.disabled = false
          },
          dataType: "json"
        });
      }
    },
    Back() {//返回选择支付
      this.dialogwxPayforVisible = false,
        this.dialogzfbPayforVisible = false,
        this.dialogdzPayforVisible = false,
        this.dialogPayforVisible = true
      this.PayTitle = '请选择支付方式'
    },
    sure() {//确认付款关闭遮罩层
      this.dialogPayforVisible = false
      this.dialogwxPayforVisible = false,
        this.dialogzfbPayforVisible = false,
        this.dialogdzPayforVisible = false,
        this.getList(this.form)
    },
    handleRemove() {//删除图片
      this.imageUrl=''
    },
    uploadBanner(file) {//上传图片
      let _this = this
      let num = 1
      if (file.size > 150000 && file.size < 500000) {
        _this.$message({
          message: '图片太大或者太小',
          type: 'error'
        });
        return
      }
      new Compressor(file, {
        quality: num,
        success(file) {
          const formData = new FormData();
          formData.append('file', file, file.name);
          let oFileReader = new FileReader();
          oFileReader.readAsDataURL(file);
          oFileReader.onload = function (e) {
            console.log(e)
            $.ajax({
              type: 'POST',
              url: DomainName + '/FileList',
              data: {
                Data: e.target.result,
                DataLength: file.size,
                FileName: file.name
              },
              complete: function (XMLHttpRequest) {
                _this.loading = false
                if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                  window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                  _this.$message(Result.Picture_Url)
                }
              },
              success: function (Result) {
                console.log(Result)
                if (Result.Status == "success") {
                  _this.imageUrl = e.target.result
                  _this.Picture_Url = Result.Picture_Url
                  // _this.imageUrl = DomainIMG + Result.Picture_Url
                  console.log(_this.imageUrl)
                  _this.$message.success('上传成功')
                } else {
                  _this.$message.error('上传失败')
                }
              },
              error: function () {
                _this.$message.error("操作失败，请稍后再试")
              },
              dataType: "json"
            });
          }
        },
        error(err) {
          console.log(err.message);
        },
      });
    },
    UploadImg() {//上传图片
      let _this = this
      this.loading = true
      $.ajax({
        type: 'POST',
        url: DomainName + '/ElectronicRemittance?token=' + $.cookie('token'),
        data: {
          Picture_URL: _this.Picture_Url,
          Purchase_Amount: _this.Paystages.Purchase_Amount,
          Collection_SerialNumber: _this.Data,
        },
        success: function (Result) {
          console.log(Result)
          if (Result.Status == 'success') {
            _this.loading = false
            _this.dialogPayforVisible = false
            _this.dialogwxPayforVisible = false,
              _this.dialogzfbPayforVisible = false,
              _this.dialogdzPayforVisible = false,
              _this.getList(_this.form)
          }
        },
        error: function () {
          _this.$message.error("操作失败，请稍后再试")
        },
        dataType: "json"
      });
    },
    Pricethousands(num){//转千分位
      return thousands(num)
    },
  },
})